<template>
  <div class="user-list-container">
    <el-form :inline="true" :model="searchFrom" class="demo-form-inline">
      <el-form-item label="用户编码">
        <el-input v-model="searchFrom.userCode"></el-input>
      </el-form-item>
      <el-form-item label="用户名称">
        <el-input v-model="searchFrom.userName"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="doSearch">查询</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="index" label="序号" width="50"></el-table-column>
      <el-table-column prop="userCode" label="用户编码">
      </el-table-column>
      <el-table-column prop="userName" label="用户名称">
      </el-table-column>
      <el-table-column prop="status" label="状态" :formatter="formatterStatus">
      </el-table-column>
      <el-table-column prop="phone" label="手机号">
      </el-table-column>
      <el-table-column prop="roleName" label="用户角色">
      </el-table-column>
      <el-table-column prop="creationDate" label="创建时间">
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-button 
            size="small" 
            @click="handleShow(scope.$index, scope.row)">查看</el-button>
          <el-button 
            size="small" 
            type="success" 
            v-if="scope.row.status==2" 
            @click="doUpdateStatus(scope.row.id,1)">启用</el-button>
          <el-button 
            size="small" 
            type="danger" 
            v-if="scope.row.status==1"
            @click="doUpdateStatus(scope.row.id,2)">冻结</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条 -->
    <div class="pagination-block">
      <el-pagination 
        @size-change="handleSizeChange" 
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[3, 5, 10]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper" 
        :total="pagination.total">
      </el-pagination>
    </div>

    <el-dialog title="查看用户信息" v-model="showFormVisible">
      <el-form :model="showForm">
        <el-form-item label="用户编码" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.userCode"></el-input>
        </el-form-item>
        <el-form-item label="用户名称" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.status"></el-input>
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.gender"></el-input>
        </el-form-item>
        <el-form-item label="出生日期" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.birthday"></el-input>
        </el-form-item>
        <el-form-item label="手机" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="地址" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.address"></el-input>
        </el-form-item>
        <el-form-item label="用户角色" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="创建时间" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.creationDate"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="showFormVisible = false">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { updateUser } from '@/api/user'

export default {
  name: 'UserList',
  setup() {
    const searchFrom = reactive({
      userCode: "",
      userName: ""
    })

    const tableData = ref([])

    const pagination = reactive({
      currentPage: 1,
      pageSize : 3,
      total: 0
    })

    const showFormVisible = ref(false)
    const showForm = reactive({
      gender: 1,
      userCode: '',
      userName: '',
      status: '',
      birthday: '',
      phone: '',
      address: '',
      roleName: '',
      creationDate: ''
    })
    const formLabelWidth = '120px'

    function doSearch() {
      pagination.currentPage = 1
      doList()
    }

    function handleShow(index, row) {
      showFormVisible.value = true
      console.log("查看用户:", index, row)
      console.log("row.gender = " + row.gender)

      showForm.userCode = row.userCode || ''
      showForm.userName = row.userName || ''
      showForm.phone = row.phone || ''
      showForm.address = row.address || ''
      showForm.roleName = row.roleName || ''
      
      // 处理日期显示
      if (row.birthday) {
        if (typeof row.birthday === 'string') {
          // 如果包含时间信息，只显示日期部分
          showForm.birthday = row.birthday.includes(' ') ? row.birthday.split(' ')[0] : row.birthday;
        } else {
          showForm.birthday = row.birthday;
        }
      } else {
        showForm.birthday = '';
      }
      
      // 处理创建时间显示
      if (row.creationDate) {
        if (typeof row.creationDate === 'string') {
          showForm.creationDate = row.creationDate;
        } else {
          showForm.creationDate = row.creationDate;
        }
      } else {
        showForm.creationDate = '';
      }

      // 格式化性别和状态显示
      showForm.gender = row.gender == 1 ? "男" : "女"
      showForm.status = row.status == 1 ? "正常" : "冻结"
      
      console.log("处理后的showForm:", showForm)
    }

    function handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      pagination.pageSize = val
      doList()
    }

    function handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      pagination.currentPage = val
      doList()
    }

    function doList() {
      request({
        url: '/user/list',
        method: 'get',
        params: {
          currentPage: pagination.currentPage,
          pageSize: pagination.pageSize,
          userCode: searchFrom.userCode,
          userName: searchFrom.userName
        }
      }).then(resp => {
        console.log("API完整响应:", resp)
        // 由于修改了拦截器，现在需要访问 resp.data 获取后端返回的实际数据
        const responseData = resp.data;
        console.log("后端返回数据:", responseData)
        
        // 处理服务端响应的结果
        if (responseData.flag === true) {
          tableData.value = responseData.data.list
          // 赋值分页
          pagination.currentPage = responseData.data.currentPage
          pagination.pageSize = responseData.data.pageSize
          pagination.total = responseData.data.totalCount
        } else {
          ElMessage.error(responseData.message || '获取用户列表失败')
        }
      }).catch(err => {
        console.error("获取用户列表出错:", err)
        ElMessage.error('网络请求失败')
      })
    }

    function doUpdateStatus(id, status) {
      ElMessageBox.confirm('确认更改用户状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log("id = " + id)
        console.log("status = " + status)
        updateUser({
          id: id,
          status: status
        }).then(resp => {
          // 获取后端返回的实际数据
          const responseData = resp.data;
          console.log("更新用户状态响应:", responseData);
          
          if (responseData.flag === true) {
            ElMessage({
              message: responseData.message || '状态更新成功',
              type: 'success'
            })
            doList()
          } else {
            ElMessage.error(responseData.message || '状态更新失败')
          }
        }).catch(err => {
          console.error("更新用户状态出错:", err)
          ElMessage.error('网络请求失败')
        })
      }).catch(() => {
        // 取消操作
      })
    }

    function formatterStatus(row) {
      console.log("row.status = " + row.status)
      let statusStr = ""
      switch (row.status) {
        case 1:
          statusStr = "正常"
          break
        case 2:
          statusStr = "冻结"
          break
      }
      return statusStr
    }

    onMounted(() => {
      doList()
    })

    return {
      searchFrom,
      tableData,
      pagination,
      showFormVisible,
      showForm,
      formLabelWidth,
      doSearch,
      handleShow,
      handleSizeChange,
      handleCurrentChange,
      doUpdateStatus,
      formatterStatus
    }
  }
}
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.pagination-block {
  margin-top: 20px;
  text-align: right;
}
</style>